<script setup lang="ts">
import {getArticleByIdUrl, getCateGoryAndTagsUrl, updateArticleUrl} from "@/api/blog/article.ts";
import UploadPictureFiles from "@/components/UploadFile/UploadPictureFiles/index.vue";
import {getUploadFileCoverUrl} from "@/api/file";

const formData = ref({
  artId: '',
  artTitle: '',
  artTag: [],
  artCategoryId: '',
  sort: '',
  status: 0,
})

const $emit = defineEmits(['getList'])
const formRef = ref(null)
const isEdit = ref(false)
const open = ref(false)
const {proxy}: any = getCurrentInstance()
const formRules = reactive({
  artTitle: [
    {required: true, message: '请输入文章标题', trigger: 'blur'},
  ],
  artCategoryId: [
    {required: true, message: '请选择文章分类', trigger: 'blur'},
  ],
  sort: [
    {required: true, message: '请输入文章排序', trigger: 'blur'},
  ],
  artTag: [
    {required: true, message: '请输入文章内容', trigger: 'blur'},
  ],
})
// id, name + type, url
const coverFiles = ref([])

const openDialog = (data?: any) => {
  isEdit.value = (data && data.artId !== null)
  getArticleByIdUrl({artId: data.artId}).then((req: any) => {
    const result = req.data;
    Object.keys(formData.value).forEach((key) => {
      if ("artTag" == key) {
        /*根据, 分割字符串*/
        formData.value.artTag = result.artTag ? result.artTag.split(',') : [];
      } else {
        formData.value[key] = result[key]
      }
      open.value = true
    })
    coverFiles.value = result.coverFiles ? result.coverFiles.map((item: any) => {
      return {
        fileId: item.id,
        name: item.name + '.' + item.suffix,
        url: item.url
      }
    }) : []
  })
}

const closeDialog = () => {
  open.value = false
}
const submitForm = async () => {
  if (!formRef.value) return
  formRef.value?.validate((valid: any) => {
    if (valid) {
      updateArticleUrl({
        ...formData.value,
        artTag: formData.value.artTag.join(',')
      }).then((res: any) => {
        proxy.$modal.msgSuccess(res.msg)
        $emit('getList')
        closeDialog()
      })
    } else {
      proxy.$modal.msgError('请填写必填项')
    }
  })
}

const cateGoryOptions = ref([])
const tagsOptions = ref([])
onMounted(() => {
  getCateGoryAndTagsUrl().then((res: any) => {
    cateGoryOptions.value = res.data.cateGory
    tagsOptions.value = res.data.tags
  })
})

/*对外暴露方法*/
defineExpose({
  openDialog
})

</script>

<template>
  <el-dialog width="500px" :title="isEdit ? '编辑文章' : '添加文章'" v-model="open">
    <el-form ref="formRef" :model="formData" label-width="80px" :rules="formRules">
      <el-form-item label="文章标题" prop="artTitle">
        <el-input v-model="formData.artTitle" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="所在分类" prop="artCategoryId">
        <el-select v-model="formData.artCategoryId" :style="{width: '100%'}" placeholder="请选择分类">
          <el-option v-for="(item, key) in cateGoryOptions" :key="item.bcId" :label="item.bcName"
                     :value="item.bcId + ''"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标签" prop="artTag">
        <el-select v-model="formData.artTag" multiple :style="{width: '100%'}" placeholder="请选择标签">
          <el-option v-for="(item, key) in tagsOptions" :key="item.btId" :label="item.btName"
                     :value="item.btId + ''"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章排序" prop="sort">
        <el-input-number v-model="formData.sort" :style="{width: '100%'}" :min="1" :max="1000000"
                         label="排序"></el-input-number>
      </el-form-item>
      <el-form-item label="封面图片" prop="artContent">
        <UploadPictureFiles
            v-model:fileData="coverFiles"
            :uploadUrl="getUploadFileCoverUrl(formData.artId)"
        ></UploadPictureFiles>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="formData.status === 0" type="success" @click="() => {
          formData.status = 1
          submitForm()
        }">发 布</el-button>
        <el-button v-else type="danger" @click="() => {
          formData.status = 0
          submitForm()
        }">取消发布</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
